package com.km.team.phsystem.web.controller;

import com.km.team.phsystem.beans.pojo.PhWindow;
import com.km.team.phsystem.beans.pojo.PhWindowExample;
import com.km.team.phsystem.beans.vo.AccountVo;
import com.km.team.phsystem.beans.vo.PhWindowVo;
import com.km.team.phsystem.beans.vo.ResponseData;
import com.km.team.phsystem.beans.vo.UpdateWindowVo;
import com.km.team.phsystem.common.constants.Constants;
import com.km.team.phsystem.common.utils.StrUtils;
import com.km.team.phsystem.common.utils.UUIDUtils;
import com.km.team.phsystem.web.controller.base.BaseController;
import com.km.team.phsystem.web.utils.ResponseDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Hashtable;
import java.util.List;

@Api(value="/window",description = "窗口账户操作API",produces ="application/json, application/xml")
@RestController
@RequestMapping("/window")
public class PhWindowController extends BaseController<PhWindowController> {

    //用户登录后返回的对象
    private class LoginData {
        /**
         * 账号
         */
        private String account;
        /**
         * 系统分配的令牌
         */
        private String token;

        public String getAccount() {
            return account;
        }

        public void setAccount(String account) {
            this.account = account;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public LoginData(String account, String token) {
            this.account = account;
            this.token = token;
        }
    }

    //用于存储帐号和token的对应关系；
    private  Hashtable<String,PhWindow> AccountToken =new Hashtable<String,PhWindow>();

    @ApiOperation(value = "新建窗口及用户", notes = "")
    @PostMapping("/add")
    public ResponseData add(@RequestBody @Valid PhWindowVo vo, BindingResult bindingResult) throws Exception {
       /*
       新建窗口及用户时判断用户及窗口是否重名
       * */
        if (bindingResult.hasErrors()) {
            return ResponseDataUtil.buildError(Constants.IIIEGAL_PARAMETER, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        //新建时判断窗口名称是否重复
        PhWindowExample searchByWindowNameExample = new PhWindowExample();
        searchByWindowNameExample.or().andWindowNameEqualTo(vo.getWindowName());
        List<PhWindow> phWindowList = phWindowService.getWindowList(searchByWindowNameExample);
        if (!CollectionUtils.isEmpty(phWindowList)) {
            return ResponseDataUtil.buildError(Constants.ERROR, "指定的窗口名称已存在！");
        }
        //新建时判断账户名是否重复
        PhWindowExample searchByAccountExample = new PhWindowExample();
        searchByAccountExample.or().andAccountEqualTo(vo.getAccount());
        List<PhWindow> AccountList = phWindowService.getWindowList(searchByAccountExample);
        if (!CollectionUtils.isEmpty(AccountList)) {
            return ResponseDataUtil.buildError(Constants.ERROR, "指定的账户名称已存在！");
        }
        int i = phWindowService.add(vo);
        if (i > 0) {
            return ResponseDataUtil.buildSuccess();
        }
        else {
            return ResponseDataUtil.buildError(Constants.ERROR, "新建窗口失败！");
        }
    }


    @ApiOperation(value = "窗口用户登录", notes = "")
    @PostMapping("/login")
    public ResponseData login(@RequestBody @Valid AccountVo vo, BindingResult bindingResult, HttpSession session) throws Exception {
        if (bindingResult.hasErrors()) {
            return ResponseDataUtil.buildError(Constants.IIIEGAL_PARAMETER, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        PhWindowExample loginUser = new PhWindowExample();
        loginUser.or().andAccountEqualTo(vo.getAccount()).andPasswordEqualTo(StrUtils.getMD5(vo.getPassword()));
        List<PhWindow> userList = phWindowService.getWindowList(loginUser);
        String token = "";
        if (userList.size() == 1) {
            PhWindow phWindow=userList.get(0);
            if (!phWindow.getStatus())
                return ResponseDataUtil.buildError(Constants.ERROR, "窗口已停用，不允许登录！");
            //保存登录成功的用户至session
            session.setAttribute(Constants.USER_SESSION, userList.get(0));
            token = UUIDUtils.getUUID();
            AccountToken.put(token, userList.get(0));
        } else {
            return ResponseDataUtil.buildError(Constants.ERROR, "用户名或密码错误！");
        }
        LoginData loginData = new LoginData(vo.getAccount(), token);
        return ResponseDataUtil.buildSuccess(loginData);
    }


    @ApiOperation(value = "获取窗口列表", notes = "")
    @GetMapping("getWindowList")
    public ResponseData getWindowList() throws Exception {
        PhWindowExample phWindowExample = new PhWindowExample();
        List<PhWindow> phWindowList = phWindowService.getWindowList(phWindowExample);
        //去除Admin账户
        for (PhWindow phWindow : phWindowList) {
            if (phWindow.getAccount().equals("admin")) {
                phWindowList.remove(phWindow);
                break;
            }
        }
        return ResponseDataUtil.buildSuccess(phWindowList);
    }


    @ApiOperation(value = "更新窗口用户信息", notes = "")
    @PostMapping("/update")
    public ResponseData update(@RequestBody @Valid UpdateWindowVo vo, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return ResponseDataUtil.buildError(Constants.IIIEGAL_PARAMETER, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (null == vo.getId()) {
            return ResponseDataUtil.buildError(Constants.ERROR, "更新数据时ID不允许为空！");
        }
        if ("admin".equals(vo.getAccount())) {
            return ResponseDataUtil.buildError(Constants.ERROR, "不允许把账号名设置为admin！");
        }
        PhWindow phWindow = new PhWindow();
        BeanUtils.copyProperties(vo, phWindow);
        int i = phWindowService.updateAccount(phWindow);
        if (i > 0) {
            return ResponseDataUtil.buildSuccess();
        }
        else {
            return ResponseDataUtil.buildError(Constants.ERROR, "更新失败！");
        }

    }

    @ApiOperation(value = "删除窗口用户信息", notes = "删除窗口及账户数据,ID不允许为空" )
    @PostMapping("/delete")
    public ResponseData delete(@RequestBody PhWindow phWindow) throws Exception {
        if ( phWindow.getId()==null ||  "".equals(phWindow.getId())) {
            return ResponseDataUtil.buildError(Constants.IIIEGAL_PARAMETER, "删除数据时ID不允许为空！");
        }
        PhWindowExample phWindowExample = new PhWindowExample();
        phWindowExample.or().andIdEqualTo(phWindow.getId());
        List<PhWindow> windowList = phWindowService.getWindowList(phWindowExample);
        if (windowList.size() > 0) {
            if ("admin".equals(windowList.get(0).getAccount())) {
                return ResponseDataUtil.buildError(Constants.ERROR, "admin用户不允许删除！");
            }
        }
        int i = phWindowService.delete(phWindowExample);
        if (i > 0) {
            return ResponseDataUtil.buildSuccess();
        }
        else {
            return ResponseDataUtil.buildError(Constants.ERROR, "删除用户失败！");
        }
    }

    @ApiOperation(value = "根据token获取用户", notes = "")
    @GetMapping("/getAccountByToken")
    public ResponseData getAccountByToken(String token) throws Exception {
        if(token==null || "".equals(token)) {
            return ResponseDataUtil.buildError(Constants.ERROR, "token不允许为空！");
        }
        PhWindow phWindow = AccountToken.get(token);
        if (phWindow==null) {
            return ResponseDataUtil.buildError(Constants.ERROR, "找不到对应的用户！");
        }
        phWindow.setPassword(null);
        return ResponseDataUtil.buildSuccess(phWindow);
    }

}
